package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.UserLoginService;
import com.usian.common.exception.code.AdminStatusCode;
import com.usian.common.exception.CatchCustomException;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.admin.vos.AdUserVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.common.BCrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class AdUserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {


    @Override //(noRollbackFor = {NullPointerException.class})
    @Transactional
    public ResponseResult login(AdUserDto dto) {
        //1. 检查参数
        if(dto==null){
            CatchCustomException.catchs(AdminStatusCode.PARAM_FAIL,"参数非法");
        }
        //2. 判断用户名和密码
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            CatchCustomException.catchs(AdminStatusCode.PARAM_FAIL,"参数非法");
        }
        //根据用户名查询
        AdUser adUser = this.getOne(new LambdaQueryWrapper<AdUser>().eq(AdUser::getName,dto.getName()));
        if(adUser == null){
            CatchCustomException.catchs(AdminStatusCode.USERNAME_NULL,"用户名不正确");
        }
        // 状态必须是可用状态  才允许登录
        if(adUser.getStatus() != 9){
            CatchCustomException.catchs(AdminStatusCode.LOGIN_STATUS,"当前登录账户以被锁定，需要联系管理员");
        }
        //判断密码
        if(!BCrypt.checkpw(dto.getPassword(),adUser.getPassword())){
            CatchCustomException.catchs(AdminStatusCode.PASSWORD_FAIL,"密码错误");
        }
        // 签发token令牌
        String token =  AppJwtUtil.getToken(Long.parseLong(adUser.getId()+""));
        //封装用户使用的信息
        AdUserVo adUserVo = JSON.parseObject(JSON.toJSONString(adUser),AdUserVo.class);
        adUserVo.setToken(token);
        adUserVo.setPassword("");
        //链接数据库 修改最后一次登录时间
        adUser.setLoginTime(new Date());
        this.updateById(adUser);
        return ResponseResult.okResult(adUserVo);
    }



}
